"""交易相关路由"""

from flask import Blueprint, request, current_app
from flasgger import swag_from
from utils.response import create_response
from utils.exceptions import BlockchainMiddlewareException
from models.transaction import TransactionModel
from utils.cache_manager import get_cache, set_cache
from utils.logger import get_logger

logger = get_logger(__name__)

transaction_bp = Blueprint('transaction', __name__)

@transaction_bp.route('/chains/<chain_type>/transactions/<tx_hash>', methods=['GET'])
@swag_from({
    'tags': ['Transaction'],
    'summary': '通过交易哈希查询交易信息',
    'description': '从数据库中查询已持久化的交易信息',
    'security': [{'ApiKeyAuth': []}],
    'parameters': [
        {
            'name': 'tx_hash',
            'in': 'path',
            'type': 'string',
            'required': True,
            'description': '交易哈希'
        }
    ],
    'responses': {
        200: {
            'description': '成功返回交易信息',
            'schema': {
                'type': 'object',
                'properties': {
                    'success': {'type': 'boolean'},
                    'data': {
                        'type': 'object',
                        'properties': {
                            '_id': {'type': 'string'},
                            'tx_hash': {'type': 'string'},
                            'chain_type': {'type': 'string'},
                            'contract_address': {'type': 'string'},
                            'method': {'type': 'string'},
                            'params': {'type': 'object'},
                            'result': {'type': 'object'},
                            'key': {'type': 'string'},
                            'value': {'type': 'string'},
                            'timestamp': {'type': 'string'},
                            'status': {'type': 'string'}
                        }
                    },
                    'requestId': {'type': 'string'}
                }
            }
        },
        404: {'description': '交易不存在'},
        500: {'description': '查询失败'}
    }
})
def get_transaction_by_hash(chain_type, tx_hash):
    """通过交易哈希查询交易信息"""
    try:
        # 先从缓存中查找
        cache_key = f"transaction:{tx_hash}"
        cached_transaction = get_cache(chain_type, cache_key)
        
        if cached_transaction:
            logger.debug(f"Transaction {tx_hash} found in cache for chain {chain_type}")
            return create_response(data=cached_transaction)
        
        # 缓存中没有，从数据库查询
        logger.debug(f"Transaction {tx_hash} not in cache, querying database for chain {chain_type}")
        transaction_model = TransactionModel(current_app.mongo_db)
        
        # 查询交易信息，同时过滤区块链类型
        transaction = transaction_model.get_transaction_by_hash_and_chain(tx_hash, chain_type)
        
        if not transaction:
            return create_response(
                success=False,
                error_code='TRANSACTION_NOT_FOUND',
                error_message=f'Transaction {tx_hash} not found in {chain_type} blockchain',
                status_code=404
            )
        
        # 将查询结果缓存5分钟
        set_cache(chain_type, cache_key, transaction, timeout=300)
        logger.debug(f"Transaction {tx_hash} cached for chain {chain_type}")
        
        return create_response(data=transaction)
        
    except Exception as e:
        logger.error(f"Error querying transaction {tx_hash} for chain {chain_type}: {str(e)}")
        return create_response(
            success=False,
            error_code='TRANSACTION_QUERY_ERROR',
            error_message=str(e),
            status_code=500
        )

@transaction_bp.route('/transactions', methods=['GET'])
@swag_from({
    'tags': ['Transaction'],
    'summary': '查询交易列表',
    'description': '根据条件查询交易列表',
    'security': [{'ApiKeyAuth': []}],
    'parameters': [
        {
            'name': 'chain_type',
            'in': 'query',
            'type': 'string',
            'required': False,
            'description': '区块链类型过滤'
        },
        {
            'name': 'contract_address',
            'in': 'query',
            'type': 'string',
            'required': False,
            'description': '合约地址过滤'
        },
        {
            'name': 'limit',
            'in': 'query',
            'type': 'integer',
            'required': False,
            'default': 100,
            'description': '返回数量限制'
        },
        {
            'name': 'skip',
            'in': 'query',
            'type': 'integer',
            'required': False,
            'default': 0,
            'description': '跳过数量'
        }
    ],
    'responses': {
        200: {
            'description': '成功返回交易列表',
            'schema': {
                'type': 'object',
                'properties': {
                    'success': {'type': 'boolean'},
                    'data': {
                        'type': 'object',
                        'properties': {
                            'transactions': {
                                'type': 'array',
                                'items': {
                                    'type': 'object',
                                    'properties': {
                                        '_id': {'type': 'string'},
                                        'tx_hash': {'type': 'string'},
                                        'chain_type': {'type': 'string'},
                                        'contract_address': {'type': 'string'},
                                        'method': {'type': 'string'},
                                        'timestamp': {'type': 'string'},
                                        'status': {'type': 'string'}
                                    }
                                }
                            },
                            'total': {'type': 'integer'}
                        }
                    },
                    'requestId': {'type': 'string'}
                }
            }
        },
        500: {'description': '查询失败'}
    }
})
def get_transactions():
    """查询交易列表"""
    try:
        # 获取查询参数
        chain_type = request.args.get('chain_type')
        contract_address = request.args.get('contract_address')
        limit = int(request.args.get('limit', 100))
        skip = int(request.args.get('skip', 0))
        
        # 初始化交易模型
        transaction_model = TransactionModel(current_app.mongo_db)
        
        # 根据条件查询
        if contract_address:
            transactions = transaction_model.get_transactions_by_contract(
                contract_address, limit, skip
            )
        elif chain_type:
            transactions = transaction_model.get_transactions_by_chain(
                chain_type, limit, skip
            )
        else:
            # 查询所有交易
            transactions = transaction_model.get_all_transactions(limit, skip)
        
        # 获取总数
        total = transaction_model.get_transaction_count(chain_type)
        
        return create_response(data={
            'transactions': transactions,
            'total': total,
            'limit': limit,
            'skip': skip
        })
        
    except Exception as e:
        return create_response(
            success=False,
            error_code='TRANSACTION_LIST_ERROR',
            error_message=str(e),
            status_code=500
        )